package com.yuejiekeji.photowall.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.yuejiekeji.photowall.common.BizException;
import com.yuejiekeji.photowall.common.Const;
import com.yuejiekeji.photowall.entity.User;
import com.yuejiekeji.photowall.entity.UserSignInLog;
import com.yuejiekeji.photowall.entity.remote.res.WxCode2SessionRes;
import com.yuejiekeji.photowall.entity.req.SignInReq;
import com.yuejiekeji.photowall.entity.req.SignUpReq;
import com.yuejiekeji.photowall.entity.res.SignInRes;
import com.yuejiekeji.photowall.enums.ERegisterType;
import com.yuejiekeji.photowall.enums.EResponseCode;
import com.yuejiekeji.photowall.mapper.UserMapper;
import com.yuejiekeji.photowall.mapper.UserSignInLogMapper;
import com.yuejiekeji.photowall.service.ConfigService;
import com.yuejiekeji.photowall.service.UserService;
import com.yuejiekeji.photowall.util.JWTUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;



    @Resource
    private UserSignInLogMapper userSignInLogMapper;


    @Resource
    private RedisTemplate redisTemplate;



    @Resource
    private ConfigService configService;


    @Override
    public void signUp(SignUpReq req){
        User user = new User();
        user.setUsername(req.getLoginName());
        user.setPassword(SecureUtil.md5(req.getPassword() + Const.PASSWORD_SALT));
        user.setIp(req.getIp());
        userMapper.insertSelective(user);
    }


    @Override
    public SignInRes signIn(SignInReq req){
        String pwd = SecureUtil.md5(req.getPassword() + Const.PASSWORD_SALT);

        User user = null;
        if (Objects.isNull(user)){
            throw new BizException(EResponseCode.ACCOUNT_ERROR.getCode());
        }

        String token = JWTUtil.getToken(user);

        SignInRes signInRes = SignInRes.builder()
                .id(user.getId())
                .loginName(user.getUsername())
                .mobile(user.getPhone())
                .nick(user.getNick())
                .avatar(user.getAvatar()).token(token)
                .build();


        UserSignInLog signInLog = new UserSignInLog();
        signInLog.setUid(user.getId());
        signInLog.setIp(req.getIp());
        signInLog.setTime(System.currentTimeMillis());

        userSignInLogMapper.insertSelective(signInLog);


        redisTemplate.opsForValue().set(Const.RedisKeyPrefix.LOGIN_USER + user.getId(),token);

        return signInRes;
    }



    @Override
    public SignInRes wxLogin(String code, String avatar, String nick, String ip){

        Map<String, String> wxConfig = configService.getMapByType("wx_config");

        String url = wxConfig.get("url");

        Map<String,Object> params = new HashMap<>();
        params.put("appid",wxConfig.get("appid"));
        params.put("secret",wxConfig.get("secret"));
        params.put("js_code",code);
        params.put("grant_type","authorization_code");

        String res = HttpUtil.get(url,params);
        WxCode2SessionRes wxCode2SessionRes =  JSON.parseObject(res, WxCode2SessionRes.class);

        User user = userMapper.getByUserName(wxCode2SessionRes.getOpenid());

        if (Objects.isNull(user)){
            user = new User();
            user.setUsername(wxCode2SessionRes.getOpenid());
            user.setAvatar(avatar);
            user.setNick(nick);
            user.setIp(ip);
            user.setRegisterType(ERegisterType.WECHAT.getCode());
            userMapper.insertSelective(user);
        }
        UserSignInLog userSignInLog = new UserSignInLog();
        userSignInLog.setUid(user.getId());
        userSignInLog.setIp(ip);
        userSignInLog.setTime(System.currentTimeMillis());
        userSignInLogMapper.insertSelective(userSignInLog);



        String token = JWTUtil.getToken(user);

        SignInRes signInRes = SignInRes.builder()
                .id(user.getId())
                .loginName(user.getUsername())
                .mobile(user.getPhone())
                .nick(user.getNick())
                .avatar(user.getAvatar()).token(token)
                .build();



        redisTemplate.opsForValue().set(Const.RedisKeyPrefix.LOGIN_USER + user.getId(),token);


        return signInRes;

    }

}
